Python脚本获取命令行参数getopt、gnu 您所在的位置:网站首页 python 获取参数 Python脚本获取命令行参数getopt、gnu

Python脚本获取命令行参数getopt、gnu

2023-03-26 12:51| 来源: 网络整理| 查看: 265

问题

python脚本如何获取命令行参数,包括选项及非选项参数,例如:

python client.py -b -t timeout host port python client.py -h python client.py --help 相关模块

python提供了sys模块获取参数,getopt模块对参数进行解析。

sys.argv:命令行参数,包含脚本名称本身 sys.argv[0]:脚本名称本身,如client.py sys.argv[1:]:命令行参数,不包括脚本名称 getopt.getopt():解析命令行参数 getopt.gnu_getopt():解析命令行参数,选项和非选项可以混合在一起 getopt.GetoptError:解析命令行参数时的异常名称 getopt.error:getopt.GetoptError的别称,向下兼容用 函数原型及说明

getopt和gnu_getopt的原型如下: getopt(args,options[,long_options]) gnu_getopt(args,options[,long_options])

args是参数列表,通常使用sys.argv[1:],当然也可以自己构造一个参数列表,如myargv=['-t', '60', '127.0.0.1', '8080'] options是短参数,如-h,-v,-p 80。 long_options是长参数,如--help 函数调用说明

举例说明,对于如下调用:

try: opts, args = getopt.gnu_getopt(sys.argv[1:], "bht:", ['help','timeout=']) except getopt.GetoptError as e: print e sys.exit()

"bht:": 当一个选项只是表示开关状态(不带附加参数)时,分析串中只写选项字符。当选项带附加参数时,分析串中写入选项字符同时后面加一个":"号。所以"bht:"就表示"b"和"h"是开关选项;"t:"则表示后面带一个参数。

调用getopt或gnu_getopt函数时,函数返回两个列表:opts和args。opts为分析出的格式信息。args为不属于格式信息的剩余的命令行参数。opts是一个两元组的列表。每个元素为:(选项串,附加参数)。如果没有附加参数则为空串''。

使用长格式分析串列表:['help','timeout=']。长格式串也可以有开关状态,即后面不跟"="号。如果跟一个等号则表示后面还有一个参数。这个例子中,"help"是一个开关选项;"timeout="则表示后面带一个参数。

整个过程使用异常来包含,这样当分析出错时,就可以打印出用法信息来通知用户如何使用这个程序。

执行程序时,对于短格式,"-"号后面要紧跟一个选项字母。如果还有此选项的附加参数,可以用空格分开,也可以不分开。长度任意,也可以用引号。以下是正确的: -o -oa -obbbb -o bbbb -o'ccc' -o "a b"

执行程序时,对于长格式,"--"号后面要跟一个单词。如果选项有附加参数,后面要紧跟"=",再加上参数,"="号前后不能有空格,或者使用空格分隔选项和附加参数,以下是正确的: --timeout=30 --timeout 30 而这些是不正确的: -- timeout=30 --timeout =30 --timeout = 30 --timeout= 30 --timeout30

getopt和gnu_getopt的区别在于,getopt是在非选项参数之后,所有的参数都被定义为非选项。而gnu_getopt则可以混用,如:client.py -t 30 127.0.0.1 8080 -b。gnu_getopt是从python 2.3开始引入的。

长选项会尽可能长的识别,例如long_options为['foo','frob'],则--fo会匹配--foo。但是--f不会匹配,而抛出GetoptError异常。

实例 #!/usr/bin/env python import sys, getopt timeout = -1 TS = 0 bandwidth = 0 def usage(): print("Usage: %s [OPTION]... [hostname] [port]" % (sys.argv[0])) print(" -b display bandwidth in bytes") print(" -h, --help print this help and exit") print(" -t, --timeout time connection timeout") print(" --timestamp display timestamp") print(" -v, --version print version information and exit") print("sys.argv=|%s|" % sys.argv) try: opts, args = getopt.gnu_getopt(sys.argv[1:], "bht:v", ['help','timeout=','version',"timestamp"]) print("opts=|%s|" % opts) print("args=|%s|" % args) except getopt.GetoptError as e: print e usage() sys.exit() for op, value in opts: if op == "-b": bandwidth = 1 if op == "-h" or op == "--help": usage() sys.exit() if op in ("-t","--timeout"): timeout = value if op == "--timestamp": TS = 1 if op in ("-v","--version"): print("%s version: 0.0.1" % sys.argv[0]) sys.exit() if len(args) != 2: print("no host or port") usage() sys.exit() host=args[0] try: port = int(args[1]) except ValueError as e: print e usage() sys.exit() print("timeout=%s, host=%s, port=%d, bandwidth=%d, TS=%d" % (timeout, host, port, bandwidth, TS)) 验证结果1

常用的调用方式

# python client.py -t 30 -b 127.0.0.1 8080 sys.argv=|['client.py', '-t', '30', '-b', '127.0.0.1', '8080']| opts=|[('-t', '30'), ('-b', '')]| args=|['127.0.0.1', '8080']| timeout=30, host=127.0.0.1, port=8080, bandwidth=1, TS=0 验证结果2

选项和非选项混合的场景

# python client.py -t 30 127.0.0.1 8080 -b sys.argv=|['client.py', '-t', '30', '127.0.0.1', '8080', '-b']| opts=|[('-t', '30'), ('-b', '')]| args=|['127.0.0.1', '8080']| timeout=30, host=127.0.0.1, port=8080, bandwidth=1, TS=0 验证结果3

无附加参数的短选项合起来写,“-b -t”可以写为“-bt”

# python client.py -bt 30 127.0.0.1 8080 sys.argv=|['client.py', '-bt', '30', '127.0.0.1', '8080']| opts=|[('-b', ''), ('-t', '30')]| args=|['127.0.0.1', '8080']| timeout=30, host=127.0.0.1, port=8080, bandwidth=1, TS=0 [root@test python]# 验证结果4

短选项与附加参数合起来写

# python client.py -bt30 127.0.0.1 8080 sys.argv=|['client.py', '-bt30', '127.0.0.1', '8080']| opts=|[('-b', ''), ('-t', '30')]| args=|['127.0.0.1', '8080']| timeout=30, host=127.0.0.1, port=8080, bandwidth=1, TS=0 验证结果5

只有短选项,且没有附加参数

# python client.py -v sys.argv=|['client.py', '-v']| opts=|[('-v', '')]| args=|[]| client.py version: 0.0.1 验证结果6

只有长选项,且没有附加参数

# python client.py --version sys.argv=|['client.py', '--version']| opts=|[('--version', '')]| args=|[]| client.py version: 0.0.1 验证结果7

--ver匹配--version

# python client.py --ver sys.argv=|['client.py', '--ver']| opts=|[('--version', '')]| args=|[]| client.py version: 0.0.1 验证结果8

无法识别选项的异常

# python client.py -i sys.argv=|['client.py', '-i']| option -i not recognized Usage: client.py [OPTION]... [hostname] [port] -b display bandwidth in bytes -h, --help print this help and exit -t, --timeout time connection timeout --timestamp display timestamp -v, --version print version information and exit 验证结果9

没有必要的附加参数的异常

# python client.py -t sys.argv=|['client.py', '-t']| option -t requires argument Usage: client.py [OPTION]... [hostname] [port] -b display bandwidth in bytes -h, --help print this help and exit -t, --timeout time connection timeout --timestamp display timestamp -v, --version print version information and exit 验证结果10

字符无法转化成数字的异常

# python client.py 127.0.0.1 8080abc sys.argv=|['client.py', '127.0.0.1', '8080abc']| opts=|[]| args=|['127.0.0.1', '8080abc']| invalid literal for int() with base 10: '8080abc' Usage: client.py [OPTION]... [hostname] [port] -b display bandwidth in bytes -h, --help print this help and exit -t, --timeout time connection timeout --timestamp display timestamp -v, --version print version information and exit 验证结果11

长选项过短无法匹配的异常

# python client.py --time 127.0.0.1 8080 sys.argv=|['client.py', '--time', '127.0.0.1', '8080']| option --time not a unique prefix Usage: client.py [OPTION]... [hostname] [port] -b display bandwidth in bytes -h, --help print this help and exit -t, --timeout time connection timeout --timestamp display timestamp -v, --version print version information and exit


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有